const connect = require('connect');
const url = require('url');

connect().use(rewrite).use(showPost).listen(3000);

function rewrite(req, res, next) {
  const path = url.parse(req.url).pathname;
  const match = path.match(/^\/blog\/posts\/(.+)/);
  if (match) {
    findPostIdBySlug(match(1), function (err, id) {
      if (err) {
        return next(err);
      }
      if (!id) {
        return next(new Error('User not found'));
      }
      req.url = `/blog/posts/${id}`;
      next();
    });
  } else {
    next();
  }
}

function showPost(req, res, next) {
  res.write(req.url);
  res.end();
}

function findPostIdBySlug(name, callback) {
  callback(new Error('error'), 1);
}
